package com.gzl.demo.utils;

import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

import java.time.LocalDateTime;
import java.time.ZoneOffset;

public class JodaTimeUtils {

    // it's thread-safe, ref: http://stackoverflow.com/a/12540298

    /**
     * yyyy-MM-dd
     */
    public static final DateTimeFormatter FORMATTER_yyyyMMdd = DateTimeFormat.forPattern("yyyy-MM-dd");

    /**
     * HH:mm
     */
    public static final DateTimeFormatter FORMATTER_HHmm = DateTimeFormat.forPattern("HH:mm");

    /**
     * HH:mm:ss
     */
    public static final DateTimeFormatter FORMATTER_HHmmss = DateTimeFormat.forPattern("HH:mm:ss");

    /**
     * yyyy-MM-dd HH:mm:ss
     */
    public static final DateTimeFormatter FORMATTER_yyyyMMddHHmmss = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");

    /**
     * yyyy-MM-dd HH:mm:ss.SZ
     */
    public static final DateTimeFormatter FORMATTER_yyyyMMddHHmmssSZ = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss.SZ");

    /**
     * yyyyMMddHHmmss
     */
    public static final DateTimeFormatter FORMATTER_yyyyMMddHHmmss_noDelimiter = DateTimeFormat.forPattern("yyyyMMddHHmmss");

    /**
     * yyyyMMdd
     */
    public static final DateTimeFormatter FORMATTER_yyyyMMdd_noDelimiter = DateTimeFormat.forPattern("yyyyMMdd");

    /**
     * MM-dd HH:mm
     */
    public static final DateTimeFormatter FORMATTER_MMddHHmm = DateTimeFormat.forPattern("MM-dd HH:mm");

    /**
     * yyyy-MM-dd HH:mm
     */
    public static final DateTimeFormatter FORMATTER_yyyyMMddHHmm = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm");

    /**
     * 把时间向下截取为小时整数, 即对小时取整, 抹掉多余的不足1小时的时间
     */
    public static DateTime withTimeAtStartOfHour(DateTime from) {
        return from.withMinuteOfHour(0).withSecondOfMinute(0).withMillisOfSecond(0);
    }

    /**
     * 获取当月第一天
     */
    public static DateTime withTimeAtStartOfMonth(DateTime from) {
        return from.withDayOfMonth(1).withHourOfDay(0).withMinuteOfHour(0).withSecondOfMinute(0).withMillisOfSecond(0);
    }

    /**
     * 获取下月第一天
     */
    public static DateTime withTimeAtStartOfNextMonth(DateTime from) {
        return withTimeAtStartOfMonth(from).plusMonths(1);
    }

    /**
     * 获取当月第一天
     */
    public static LocalDateTime withTimeAtStartOfMonth(LocalDateTime from) {
        return from.withDayOfMonth(1).withHour(0).withMinute(0).withSecond(0);
    }

    /**
     * 获取下月第一天
     */
    public static LocalDateTime withTimeAtStartOfNextMonth(LocalDateTime from) {
        return withTimeAtStartOfMonth(from).plusMonths(1);
    }

    /**
     * 将 LocalDateTime转换为时间戳
     */
    public static Long localDateTimeConvertedTimestamp(LocalDateTime localDateTime) {
        return localDateTime.toInstant(ZoneOffset.of("+8")).toEpochMilli();
    }

}
